﻿using SqlSugar;
using Sunny.UI;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Models;

namespace WinformDevFramework
{
    public partial class FrmMenu : BaseForm1
    {
        private ISysMenuServices _sysMenuServices;
        public FrmMenu(ISysMenuServices sysMenuServices)
        {
            _sysMenuServices = sysMenuServices;
            InitializeComponent();
            this.DoubleBuffered=true;
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        public override void Init()
        {
            base.Init();
            ReadOnlyControlList.Add("ltCreateBy");
            ReadOnlyControlList.Add("ldCreateDate");
            ReadOnlyControlList.Add("ltUpdateBy");
            ReadOnlyControlList.Add("ldUpdateDate");

            dataGridViewList.DoubleBuffered();
            ltMenuTitle.Label.Text = "菜单名称";
            ltIcon.Label.Text = "菜单图标";
            ltMenuUrl.Label.Text = "菜单Url";
            ltSort.Label.Text = "排序";
            ltCreateBy.Label.Text = "创建人";
            ltUpdateBy.Label.Text = "修改人";
            lcMenuType.Label.Text = "菜单类型";
            ldCreateDate.Label.Text = "创建时间";
            ldUpdateDate.Label.Text = "修改时间";
            ltIcon.TextBox.TextChanged += TextBox_TextChanged;
            dataGridViewList.CellFormatting += DataGridViewList_CellFormatting;
            uiComboTreeViewPMenu.CanSelectRootNode=true;
            //初始化父菜单数据
            var menus = GetAllMenus();
            SetParentMenu(menus);
            //初始化菜单类型
            this.lcMenuType.ComboBox.DataSource = new List<string>(){"Button","Form","Menu"};

            //初始化 数据列表 列名称
            this.dataGridViewList.DataSource=menus.OrderBy(p=>p.PermissionCode).ToList();
            this.dataGridViewList.Columns["ID"]!.HeaderText = "ID";
            this.dataGridViewList.Columns["PMenuName"]!.HeaderText = "父菜单";
            this.dataGridViewList.Columns["PMenuName"].DisplayIndex=1;
            this.dataGridViewList.Columns["Title"]!.HeaderText = "菜单名称";
            this.dataGridViewList.Columns["Title"].DisplayIndex = 2;
            this.dataGridViewList.Columns["MenuCode"]!.HeaderText = "菜单编码";
            this.dataGridViewList.Columns["PermissionCode"]!.HeaderText = "菜单权限标识";
            this.dataGridViewList.Columns["Icon"]!.HeaderText = "图标";
            this.dataGridViewList.Columns["Icon"].Visible = false;
            this.dataGridViewList.Columns["Url"]!.HeaderText = "菜单URL";
            this.dataGridViewList.Columns["SortOrder"]!.HeaderText = "排序";
            this.dataGridViewList.Columns["MenuType"]!.HeaderText = "菜单类型";
            this.dataGridViewList.Columns["CreateByName"]!.HeaderText = "创建人";
            this.dataGridViewList.Columns["CreatedDate"]!.HeaderText = "创建时间";
            this.dataGridViewList.Columns["UpdateByName"]!.HeaderText = "修改人";
            this.dataGridViewList.Columns["UpdatedDate"]!.HeaderText = "修改时间";

            this.dataGridViewList.Columns["ParentID"].Visible = false;
            this.dataGridViewList.Columns["CreatedBy"].Visible = false;
            this.dataGridViewList.Columns["UpdatedBy"].Visible = false;
            DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
            imageColumn.HeaderText = "图标";
            imageColumn.Name = "ImageColumn";
            imageColumn.DefaultCellStyle.NullValue = null;
            
            this.dataGridViewList.Columns.Add(imageColumn);

            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        private void DataGridViewList_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
        {

            if (e.RowIndex >= 0 && dataGridViewList.Columns[e.ColumnIndex] is DataGridViewImageColumn)
            {
                // 获取当前行的数据
                var rowData = dataGridViewList.Rows[e.RowIndex].DataBoundItem as sysMenu;

                // 根据行的数据设置图片
                if (rowData != null)
                {
                    // 根据需要设置图片的逻辑
                    // 这里假设你有一个名为"ImageFilePath"的属性，表示图片的文件路径
                    string imageFilePath =Application.StartupPath+"\\"+ rowData.Icon;

                    // 设置单元格的图片
                    if (!string.IsNullOrEmpty(imageFilePath)&&File.Exists(imageFilePath))
                    {
                        e.Value = Image.FromFile(imageFilePath);
                    }
                }
            }
        }

        private void TextBox_TextChanged(object? sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ltIcon.TextBox.Text))
            {
                pictureBox.Image = null;
            }
            else
            {
                if(File.Exists(Application.StartupPath + "\\" + ltIcon.TextBox.Text))
                    pictureBox.Image = Image.FromFile(Application.StartupPath+"\\"+ltIcon.TextBox.Text);
            }
        }

        /// <summary>
        /// 父菜单控件设置
        /// </summary>
        private void SetParentMenu(List<sysMenu> menus)
        {
            uiComboTreeViewPMenu.Nodes.Clear();
            List<TreeNode> nodes = new List<TreeNode>();
            foreach (var menu in menus)
            {
                TreeNode node = new TreeNode(menu.Title);
                node.Tag = menu;
                node.Name = menu.ID.ToString();
                nodes.Add(node);
            }

            foreach (var treeNode in nodes)
            {
                var menu = (sysMenu)treeNode.Tag;
                treeNode.Nodes.AddRange(nodes.Where(p => menu.ID == ((sysMenu)p.Tag).ParentID).ToArray());
            }

            uiComboTreeViewPMenu.Nodes.Add(nodes.Where(p => ((sysMenu)p.Tag).ParentID == 0).FirstOrDefault());
        }
        /// <summary>
        /// 获取所有菜单项
        /// </summary>
        /// <returns></returns>
        private List<sysMenu> GetAllMenus()
        {
            var menus = _sysMenuServices.QueryMuch<sysMenu, sysMenu, sysUser, sysUser, sysMenu>((m, pm, u1, u2) => new object[]
                {
                    JoinType.Left,m.ParentID==pm.ID,
                    JoinType.Left,m.CreatedBy==u1.ID,
                    JoinType.Left,m.UpdatedBy==u2.ID,
                },
                (m, pm, u1, u2) => new sysMenu()
                {
                    ID = m.ID,
                    CreatedBy = m.CreatedBy,
                    UpdatedBy = m.UpdatedBy,
                    ParentID = m.ParentID,
                    Title = m.Title,
                    Icon = m.Icon,
                    PMenuName = pm.Title,
                    CreateByName = u1.Fullname,
                    CreatedDate = m.CreatedDate,
                    MenuType = m.MenuType,
                    UpdatedDate = m.UpdatedDate,
                    UpdateByName = u2.Fullname,
                    SortOrder = m.SortOrder,
                    URL = m.URL,
                    MenuCode = m.MenuCode,
                    PermissionCode = m.PermissionCode,
                }
            );
            return menus;
        }
        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model=g.CurrentRow.DataBoundItem as sysMenu;
            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.ltMenuTitle.TextBox.Text = model.Title;
            this.ltMenuUrl.TextBox.Text = model.URL;
            this.ltSort.TextBox.Text = model.SortOrder.ToString();
            this.lcMenuType.ComboBox.Text = model.MenuType;
            this.ltIcon.TextBox.Text=model.Icon;
            this.ltCreateBy.TextBox.Text = model.CreateByName;
            this.ldCreateDate.DateTimePicker.Text=model.CreatedDate.ToString();
            this.ltUpdateBy.TextBox.Text = model.UpdateByName;
            this.ldUpdateDate.DateTimePicker.Text = model.UpdatedDate.ToString();
            txtMenuCode.Text=model.MenuCode;
            txtPermissionCode.Text =model.PermissionCode;
            var pmenu = _sysMenuServices.QueryById(model.ParentID);
            if (pmenu != null)
            {
                TreeNode node = new TreeNode(pmenu.Title);
                node.Name = pmenu.ID.ToString();
                node.Tag = pmenu;
                this.uiComboTreeViewPMenu.TreeView.SelectedNode = this.uiComboTreeViewPMenu.TreeView.Nodes.Find(pmenu.ID.ToString(),true).FirstOrDefault();
                this.uiComboTreeViewPMenu.Text = pmenu.Title;
                this.uiComboTreeViewPMenu.Tag = pmenu.ID;
            }

            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            ltCreateBy.TextBox.Text = AppInfo.User.Fullname;
            ldCreateDate.DateTimePicker.Text= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            ltSort.TextBox.Text = "1";
        }

        /// <summary>
        /// 设置功能按钮状态
        /// </summary>
        public override void SetToolButtonStatus(FormStatus status)
        {
            switch (status)
            {
                case FormStatus.Add:
                {
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = true;
                    btnSearch.Enabled = false;
                    SetControlStatus(this.groupBox1,true);
                    ClearControlsText(this.groupBox1);
                    break;
                }
                case FormStatus.Edit:
                {
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = true;
                    btnSearch.Enabled = false;
                    SetControlStatus(this.groupBox1, true);
                    break;
                }
                case FormStatus.View:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = true;
                    btnSave.Enabled = false;
                    btnDel.Enabled = true;
                    btnCanel.Enabled = false;
                    btnSearch.Enabled = false;
                    SetControlStatus(this.groupBox1,false);
                    break;
                }
                case FormStatus.Canel:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = true;
                    btnSave.Enabled = false;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = false;
                    btnSearch.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    break;
                }
                case FormStatus.First:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = false;
                    btnDel.Enabled = false;
                    btnCanel.Enabled=false;
                    btnSearch.Enabled = true;
                    SetControlStatus(this.groupBox1, false);
                    break;
                }
                case FormStatus.Save:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = true;
                    btnSave.Enabled = false;
                    btnDel.Enabled = true;
                    btnCanel.Enabled = false;
                    btnSearch.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    break;
                }
                case FormStatus.Del:
                {
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = false;
                    btnDel.Enabled = false;
                    btnCanel.Enabled = false;
                    btnSearch.Enabled = false;
                    SetControlStatus(this.groupBox1, false);
                    ClearControlsText(this.groupBox1);
                    break;
                }
            }
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            ltUpdateBy.TextBox.Text = AppInfo.User.Fullname;
            ldUpdateDate.DateTimePicker.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            //if (ValidateData())
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    sysMenu newMenu = new sysMenu();
                    newMenu.CreatedBy = AppInfo.User.ID;
                    newMenu.CreatedDate = DateTime.Parse(ldCreateDate.DateTimePicker.Text);
                    newMenu.Title = ltMenuTitle.TextBox.Text;
                    newMenu.URL = ltMenuUrl.TextBox.Text;
                    if (uiComboTreeViewPMenu.TreeView.SelectedNode == null)
                    {
                        newMenu.ParentID = int.Parse(uiComboTreeViewPMenu.Tag.ToString());
                    }
                    else
                    {
                        newMenu.ParentID = ((sysMenu)uiComboTreeViewPMenu.TreeView.SelectedNode.Tag).ID;
                    }
                    newMenu.SortOrder = Int32.Parse(ltSort.TextBox.Text);
                    newMenu.MenuType = lcMenuType.ComboBox.Text;
                    newMenu.Icon = ltIcon.TextBox.Text;
                    newMenu.MenuCode=txtMenuCode.Text;
                    newMenu.PermissionCode=txtPermissionCode.Text;
                    var id = _sysMenuServices.Insert(newMenu);
                    txtID.Text = id.ToString();
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                // 修改
                else
                {
                    sysMenu newMenu = _sysMenuServices.QueryById(int.Parse(txtID.Text));
                    newMenu.UpdatedBy = AppInfo.User.ID;
                    newMenu.UpdatedDate = DateTime.Parse(ldCreateDate.DateTimePicker.Text);
                    newMenu.Title = ltMenuTitle.TextBox.Text;
                    newMenu.URL = ltMenuUrl.TextBox.Text;
                    if (uiComboTreeViewPMenu.TreeView.SelectedNode == null)
                    {
                        newMenu.ParentID = int.Parse(uiComboTreeViewPMenu.Tag.ToString());
                    }
                    else
                    {
                        newMenu.ParentID = ((sysMenu)uiComboTreeViewPMenu.TreeView.SelectedNode.Tag).ID;
                    }
                    newMenu.SortOrder = Int32.Parse(ltSort.TextBox.Text);
                    newMenu.MenuType = lcMenuType.ComboBox.Text;
                    newMenu.Icon = ltIcon.TextBox.Text;
                    newMenu.MenuCode = txtMenuCode.Text;
                    newMenu.PermissionCode = txtPermissionCode.Text;
                    if (_sysMenuServices.Update(newMenu))
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                SetToolButtonStatus(formStatus);
                var menus = GetAllMenus();
                this.dataGridViewList.DataSource = menus.OrderBy(p => p.PermissionCode).ToList();
                SetParentMenu(menus);
            }
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _sysMenuServices.DeleteById(Int32.Parse(txtID.Text));
                formStatus = FormStatus.Del;
                SetToolButtonStatus(formStatus);
                var menus = GetAllMenus();
                this.dataGridViewList.DataSource = menus.OrderBy(p => p.PermissionCode).ToList();
                SetParentMenu(menus);
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
        }

        //验证数据
        public override bool ValidateData()
        {
            bool result=false;
            if (string.IsNullOrEmpty(ltMenuTitle.TextBox.Text))
            {
                MessageBox.Show("菜单名称不能为空！");
                return result;
            }
            if (!lcMenuType.ComboBox.Text.Equals("Menu")&&string.IsNullOrEmpty(uiComboTreeViewPMenu.Text))
            {
                MessageBox.Show("父菜单不能为空！");
                return result;
            }
            if (lcMenuType.ComboBox.Text.Equals("Form") && (string.IsNullOrEmpty(ltMenuUrl.TextBox.Text)))
            {
                MessageBox.Show("菜单图标不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(txtMenuCode.Text))
            {
                MessageBox.Show("菜单编码不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(txtPermissionCode.Text))
            {
                MessageBox.Show("权限标识不能为空！");
                return result;
            }
    

            result = true;
            return result;
        }

        /// <summary>
        /// 选择图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectIcon_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Application.StartupPath + "Resources\\";
            openFileDialog.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp";
            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string selectedImagePath = openFileDialog.FileName.Replace(Application.StartupPath,"");
                ltIcon.TextBox.Text= selectedImagePath;
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
    }
}
